using System;
using System.Linq;
using Kollektiv.DB;
using Kollektiv.DataModel;
using System.Net;
using System.Net.Mail;

namespace Kollektiv.Service
{	
	/// <summary>
	/// Service object for sending emails.
	/// </summary>
	public class EmailService
	{
		private string smtpHost;
		private int smtpPort;
		private string fromAddress;
		private string smtpUsername;
		private string smtpPassword;
		private bool smtpSSL;
		
		/// <summary>
		/// Initializes a new instance of the <see cref="Kollektiv.Service.EmailService"/> class.
		/// </summary>
		/// <param name='smtpHost'>
		/// Smtp host.
		/// </param>
		/// <param name='smtpPort'>
		/// Smtp port.
		/// </param>
		/// <param name='fromAddress'>
		/// Sender address.
		/// </param>
		/// <param name='smtpUsername'>
		/// Smtp username.
		/// </param>
		/// <param name='smtpPassword'>
		/// Smtp password.
		/// </param>
		/// <param name='smtpEncryption'>
		/// A smtp encryption type.
		/// </param>
		public EmailService (string fromAddress, string smtpHost, int smtpPort, string smtpUsername, string smtpPassword, bool smtpSSL)
		{
			this.smtpHost = smtpHost;
			this.smtpPort = smtpPort;
			this.fromAddress = fromAddress;
			this.smtpUsername = smtpUsername;
			this.smtpPassword = smtpPassword;
			this.smtpSSL = smtpSSL;
		}
		
		/// <summary>
		/// Sends an email.
		/// </summary>
		/// <param name='to'>
		/// Receiver email address.
		/// </param>
		/// <param name='subject'>
		/// Subject of the email.
		/// </param>
		/// <param name='body'>
		/// Content of the email.
		/// </param>
		public void Send (string to, string subject, string body)
		{
			MailMessage message = new MailMessage ();
			message.To.Add (to);
			message.Subject = subject;
			message.From = new MailAddress (this.fromAddress);
			message.Body = body;
			SmtpClient smtp = new SmtpClient (this.smtpHost, this.smtpPort);
			smtp.UseDefaultCredentials = false;
			smtp.Credentials = new NetworkCredential (this.smtpUsername, this.smtpPassword);
			smtp.EnableSsl = this.smtpSSL;
			smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
			smtp.Send (message);
		}
	}
}

